<?php
use App\Base\Annotation\Common;
/**
 * @param $class
 * @param $propertyName
 * @return Common|object|null
 */
function getAnnotationData($class,$propertyName)
{
    try {

        $reClass = new \ReflectionClass($class);
        $property = $reClass->getProperty($propertyName);
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        return $reader->getPropertyAnnotation($property,"App\Base\Annotation\Common");
    } catch (Exception $exception) {
        return null;
    }
}
function getEntityAnnotationData($class){
    try {
        $re = [];
        $reClass = new \ReflectionClass($class);
        foreach ($reClass->getProperties() as $property) {
            $re[$property->getName()] = getAnnotationData($class,$property->getName());
        }
        return $re;
    } catch (Exception $exception) {
        return [];
    }
}

//筛选条件可以用形式
//1:_where[name]=1
//2:_where[eq][name]=1
//3:_where[gt][name]=1
//4:_where[like][name]=1
//5:_where[in][name]=[1,2,3]
function createWhere4MongoDB($array){
    if (!$array) {
        return [];
    }
    $re = [];
    foreach ($array as $expression => $value) {
        if (is_array($value)) {
            foreach ($value as $key=>$dataVal) {
                if ($dataVal === "") {
                    continue;
                }
                if ($expression == "like") {
                    $expression = "regex";
                }
                if ($expression == "in") {
                    if (!is_array($dataVal)) {
                        $tmp = json_decode($dataVal,true);
                        if (!is_array($tmp)) {
                            $tmp = myExplodeNumbers($dataVal);
                            if (!is_array($tmp)) {
                                $dataVal = [$dataVal];
                            }else{
                                $dataVal = $tmp;
                            }
                        }else{
                            $dataVal = $tmp;
                        }
                    }
                }

                //猜测时间类型---->要求以At结尾
                if (substr($key,-2) === "At") {
                    //todo 更严格的检查应该正则匹配值检测是不是日期----懒，不做了
                    $dataVal = new DateTime($dataVal);
                }
                $re[$key]["$".$expression]=$dataVal;
            }
        }else{
            if ($value === "") {
                continue;
            }
            $re[$expression] = $value;
        }
    }
    return $re;

}

function createSearch4MongoDB($keywords,array $fields = [],$orOrAnd = 'or')
{
    $re=[];
    if (!$keywords || !$fields) {
        return [];
    }
    foreach ($fields as $field) {
        $re[] = [$field=>['$regex'=>"{$keywords}"]];
    }
    return [['$'.$orOrAnd=>$re]];
}


function createOrderBy(\Doctrine\ORM\QueryBuilder &$qb,$orderBy)
{
    foreach ($orderBy as $key=>$order) {
        $qb->addOrderBy("A.{$key}",$order);
    }
    return $qb;
}

function createSearch(\Doctrine\ORM\QueryBuilder &$qb,$keywords,array $fields = [],$orOrAnd = 'or')
{
    if (!$keywords || !$fields) {
        return $qb;
    }
    $search = [];
    foreach ($fields as $field) {
        $arr = explode(".",$field);//检查是否是User.name这种格式
        if (count($arr)>1) {
            createJoin($qb,$field);
            $field = createJoinAlis($field);
        }else{
            $field = "A.{$field}";
        }
        $search[] = $qb->expr()->like($field,"'%{$keywords}%'");
    }
    $expr = $orOrAnd === "or"? 'orX':'andX';
    $qb->andWhere(
        $qb->expr()->$expr(
            ...$search
        )
    );
    return $qb;
}


function createWhere(\Doctrine\ORM\QueryBuilder &$qb,$array){
    if (!$array) {
        return $qb;
    }
    $curIndex = 0;//检查是否是第一个条件，第一个条件用where 后面用andWhere
    foreach ($array as $expression => $value) {
        if (is_array($value)) {
            //检查是否需要join
            foreach ($value as $key=>$dataVal) {
                if ($dataVal === "") {
                    continue;
                }
                $arr = explode(".",$key);//检查是否是User.name这种格式
                if (count($arr)>1) {
                    $field = createJoinAlis($key);
                    createJoin($qb,$key);
                }else{
                    $field = "A.{$key}";
                }
                if ($expression == "like") {
                    $dataVal = "'%{$dataVal}%'";
                }
                if ($expression == "in") {
                    if (!is_array($dataVal)) {
                        $tmp = json_decode($dataVal,true);
                        if (!is_array($tmp)) {
                            $tmp = myExplodeNumbers($dataVal);
                            if (!is_array($tmp)) {
                                $dataVal = [$dataVal];
                            }else{
                                $dataVal = $tmp;
                            }
                        }else{
                            $dataVal = $tmp;
                        }
                    }
                }
                //猜测时间类型---->要求以At结尾
                if (substr($key,-2) === "At") {
                    $dataVal = date(YYMMDDHHIISS,strtotime($dataVal));
                    $dataVal = "$dataVal";
                }
                $qb->andWhere(
                    $qb->expr()->$expression($field,"'$dataVal'")
                );
                $curIndex++;
            }
        }else{
            if ($value === "") {
                continue;
            }
            $arr = explode(".",$expression);//检查是否是User.name这种格式
            if (count($arr)>1) {
                $field = createJoinAlis($expression);
                createJoin($qb,$expression);
            }else{
                $field = "A.{$expression}";
            }
            $qb->andWhere(
                $qb->expr()->eq($field,"'$value'")
            );
        }
        $curIndex++;
    }
    return $qb;
}

function createPage(\Doctrine\ORM\QueryBuilder $qb,$page=1,$limit=10){
    $qb->setMaxResults($limit)->setFirstResult($limit * $page - $limit);
    return $qb;
}

//todo 没考虑好
function createJoin(\Doctrine\ORM\QueryBuilder &$qb,$name){
    $arr = explode(".",$name);
    array_pop($arr);
    if (!is_array($arr)) {
        $arr = [$arr];
    }
    if (count($arr)>0) {
        //存在join
        //检查是否已经Join过 point=>section.subject.name
        $parent = "A";
        $curParentStr = "";//
        foreach ($arr as $index=>$one) {
            if ($index == 0) {//section
                $as = $one;
                if (!in_array($as,$qb->getAllAliases()?:[])) {
                    $joins[] = $as;
                    $qb->join("{$parent}.{$one}",$as);
                }
                $curParentStr = $as;
            }else{
                //section.subject
                $as = $curParentStr."_".$one;
                if (!in_array($as,$qb->getAllAliases()?:[])) {
                    $joins[] = $as;
                    $qb->join("{$curParentStr}.{$one}",$as);
                }
                $curParentStr = $as;
            }
        }
    }
}
//todo 没考虑好
function createJoinAlis($name)
{
    $arr = explode(".",$name);
    $as = "";
    foreach ($arr as $key=>$value) {
        if ($as == "") {
            $as .= $value ;
        }else{
            if ($key+1!=count($arr)) {
                $as .="_".$value;
            }else{
                $as .=".".$value;
            }
        }
    }
    return $as;
}
